import {observable, action, toJS} from 'mobx';
import * as API from '../../api/netdisk';
import {Tools,ListView, Modal,Toast, Bubble, ActionSheet} from 'weaver-mobile';
import DocConstant from "../../util";
import * as HistoryApi from '../../api/news';
import { Browser,Share,SearchPage,ListViewPage } from 'weaver-mobile-page';
const getLabel = Tools.getLabel;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

export default class ListStore {
  netdiskStore = null;
  path = null;
  parent = null;
  @observable categoryInfo = null;
  @observable searchCategoryInfo = null;
  @observable browser;
  @observable datasource = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
  });
  @observable pageNum = 0;
  @observable child = null;
  @observable loading = true;
  @observable inputElliVisible = false;
  
  @observable chooseIds = [];
  @observable chooseRows = [];
  @observable isOpenFile = false; //判断当前附件是否是打开状态
  @observable attachTitle = '';
  folderList = [];
  fileList = [];
  
  @observable uploadList = [];
  @observable netdiskListRefreshing = false;//下拉刷新状态
  
  @observable categoryBrowser;
  @observable categoryOper = {};//云盘目录浏览按钮页面操作
  browserOper = {};//系统目录浏览按钮页面操作
  shareStore = null;
  @observable shareData;
  shareParams;

  @observable myShareSearchPage; //我的分享对象页面的搜索page
  @observable myDiskSearchPage;
  shareSearchType = 8;//我的分享对象列表搜索类型
  searchType = 7;  //云盘文件搜索类型
  @observable searchKey={}; //我的分享对象搜索条件
  @observable myDiskSearchKey={};
  @observable shareObjLVPStore; //我的分享页面列表store
  @observable shareObjChooseIds = []; //我的分享页面选中的id集合
  @observable shareObjRows = []; //我的分享页面选中的行数据集合
  @observable shareObjPageData; //点击进入我的分享页面的目录信息
  @observable canReader = true; //判断当前的云盘目录是否可以访问
  @observable shareCancle = false; //分享被取消
  @observable fileDel = false; //文件被删除
  @observable currentPageNum=1;//当前页数
  
  
  constructor(params) {
    if (params) {
      const {categoryInfo, netdiskStore, parent} = params;
      this.netdiskStore = netdiskStore;
      if(categoryInfo){
        this.categoryInfo = {id:categoryInfo.id,parentId:categoryInfo.parentId,name:categoryInfo.name}
      }
      if (parent) {
        this.parent = parent;
      }
    }
  }
  
  @action
  init = (params) =>{
    let resource = params && (params.resource ||'');
    let fid = params && (params.fid ||'');
    let type = params && (params.type ||'');
    if(resource === 'em' && type === 'folder'){
      this.getShareIsReader({fid,type}).then(()=>{
      })
    }
  }

  @action
  initBrowser = (path,rowData) => {
    let id = this.categoryInfo?this.categoryInfo.id:'' || 'root';
    this.categoryBrowser = new Browser.Store({ route: path + '/category', id});
    this.browser = new Browser.Store({ route: path + '/tree', id});
    this.shareStore = new Share.Store({route: path + '/share', id});
    this.myShareSearchPage = new SearchPage.Store({ route: path + '/myshare/userlist/history',id});
    this.shareObjLVPStore = new ListViewPage.Store({ route: path + '/myshare/userlist' });
    this.shareObjLVPStore.haveCheck = true;
    this.path = path;


    this.myDiskSearchPage = new SearchPage.Store({ route: path+'/history' }); 

    this.updateList();
  }

  @action
  getMyList = (params) => {
    this.loading = true;
    return this.getList(params);
  }

  getMyShareList = (params) => {
    this.loading = true;
    return this.getList(params);
  }
  
  getWorkmateShareList = (params) => {
    this.loading = true;
    return this.getList(params);
  }
  
  getList = (params) => {
    let isScroll = (params && params.isScroll) ?params.isScroll : "0";
    this.netdiskListRefreshing = true;
    let view = this.netdiskStore.selectedTab;
    let id = (params && params.folderid)?params.folderid:(this.categoryInfo?this.categoryInfo.id : "");
    if(view==='disk'){
      return API.getMyList({...params, view,folderid:id}).then((result) => {
          if(isScroll==="1"){
            this.setScrollResult(result, params);
          }else{
            this.setQueryResult(result, params);
          }
          
        });
    }else if(view==='myShare'){
      return API.getMyShareList({...params, view,folderid:id}).then((result) =>{
        if(isScroll==="1"){
          this.setScrollResult(result, params);
        }else{
          this.setQueryResult(result, params);
        }
      });
    }else if(view==='shareMy'){
      return API.getWorkmateShareList({...params, view,folderid:id}).then((result) =>{
        if(isScroll==="1"){
          this.setScrollResult(result, params);
        }else{
          this.setQueryResult(result, params);
        }
      });
    }
  }
  
  //云盘目录的查询结果
  setQueryResult = (result, params) => {
    this.loading = false;
    this.folderList = result.folders;
    this.fileList = result.files;
    this.netdiskListRefreshing = false;
    this.currentPageNum = 1;
    this.updateList();
  }
  setScrollResult=(result,params)=>{
    this.loading = false;
    let folderList = toJS(this.folderList);
    let fileList = toJS(this.fileList);
    folderList = [...folderList,...result.folders];
    fileList=[...fileList,...result.files]
    this.folderList = folderList;
    this.fileList = fileList;
    this.netdiskListRefreshing = false;
    this.updateList();
  }


  // 右侧按钮组
  getRightButton = (path,rowData, history) => {
    let buttons = [];
    if (this.netdiskStore.selectedTab === 'disk') {
      buttons.push({
        text: getLabel(17499, "更多"),
        onPress: () => {
          ActionSheet.showActionSheetWithOptions({
              options: [{
                content: getLabel(19827, '重命名'),
                onClick: () => {
                  Modal.prompt(
                    getLabel(19827, '重命名'),
                    '',
                    [{text: getLabel(31129, "取消")}, {text: getLabel(826, "确定"),
                      onPress: (text) => {
                        if (!text) {
                          Toast.fail(getLabel(129186, "请输入目录名称"), 1, null, false);
                          return new Promise((resolve, reject) => reject(getLabel(129186, "请输入目录名称")));
                        }
                        let params = { 
                          renameType: rowData.type
                        };
                        if (rowData.type === 'folder') {
                          params.categoryid = rowData.id;
                          params.categoryname = text;
                        } else {
                          params.fileName = text;
                          params.imagefileid = rowData.id;
                          params.categoryid = this.categoryInfo ? this.categoryInfo.id : '';
                        }
                        API.rename(params).then(() => {
                          this.getList();
                        })
                      }}],
                    'default',
                    rowData.title,
                    [getLabel(84078, '请输入名称')],
                  );
                  this.inputElliVisible = false;
                }
              }, {
                content: getLabel(129168, '移动到'),
                onClick: () => {
                  this.goCategoryBrowser((rowData, id, name) => {
                    let params = {folderid: id};
                    if (rowData.type === 'folder') {
                      params.folderids = rowData.id;
                    } else {
                      params.fileids = rowData.id;
                    }
                    API.move(params).then((result) => {
                      Bubble.success(getLabel(30700, '操作成功'));
                      this.getList();
                    });
                  }, history, rowData, {noClick: rowData.id})
                }
              }, {
                content: getLabel(31129, '取消'),
                onClick: () => {}
              }],
              cancelButtonIndex: 2,
              maskClosable: true,
              'data-seed': 'logId',
              wrapProps,
            });
        },
        className: 'wea-doc-netdisk-right-button',
        style: { backgroundColor: '#999999',},
      });
      if (DocConstant.isApp()) {
        buttons.push({
          text: getLabel(126091, "分享"),
          onPress: () => {
            this.shareParams = {};
            if (rowData.type === 'file') {
              this.shareParams.fileids = rowData.id;
            } else {
              this.shareParams.folderids=rowData.id;
            }
            this.setShareData([{
                content: rowData.name, // 分享标题（必填）
                desc: "", // 分享描述（非必填）
                sysid: window.localStorage.emobile_ec_id, // EM中添加的集成系统的ID (必填: 按照demo给的传)
                linkurl: rowData.type === 'file' ?  // 消息链接地址（必填）
                  `/spa/document/static4mobile/index.html#/netdisk/file/attach/${rowData.id}?resource=${'em'}&type=${'file'}&fid=${rowData.id}`:
                  `/spa/document/static4mobile/index.html#/netdisk/${rowData.id}?resource=${'em'}&type=${'folder'}&fid=${rowData.id}`
                ,
                // linkurl_pc: ``, //PC端消息链接地址，如果没有则取linkurl值
                canforward:1, // 消息是否允许转发 1：是（默认） 0：否
                callbackurl:`/api/networkdisk/clouddisk/share?${rowData.type === 'file' ? 'fileids' : 'folderids'}=${rowData.id}`, // 消息转发回调地址（非必填）
                opentype:1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                opentype_pc:rowData.type === 'file' ? 2 : 1, //PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                sharetype:rowData.type === 'file' ? "pdoc" : "folder", // 分享数据类型："doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                shareid: rowData.id // 分享的数据ID（必填）
              }]);
            history.push(this.shareStore.path);
          },
          className: 'wea-doc-netdisk-right-button',
          style: { backgroundColor: '#FF9903',},
        });
      }
      
      buttons.push({
        text: getLabel(114, '发布'),
        onPress: ()=>this.goBrowser((rowData, id, name) => {
          let params = {folderid: id};
          if (rowData.type === 'folder') {
            params.folderids = rowData.id;
          } else {
            params.fileids = rowData.id;
          }
          this.publish(id,rowData)
        }, history, rowData),
        className: 'wea-doc-netdisk-right-button',
        style: { backgroundColor: '#2285FE',},
      });
      buttons.push({
        text: getLabel(91, "删除"),
        onPress: () => this.delForSingle(rowData),
        className: 'wea-doc-netdisk-right-button',
        style: { backgroundColor: '#FE0103',},
      });
    } else if (this.netdiskStore.selectedTab === 'myShare') {
      //我的分享列表只能删除被分享的目录，不能删除其下的目录
      if(!this.categoryInfo){
        buttons.push({
          text: getLabel(390469,'查看分享对象'),
          className: 'wea-doc-netdisk-right-button',
          style: { backgroundColor: '#2285FE',},
          onPress: () => this.getShareWithList(history,rowData)
        });
        buttons.push({
          text: getLabel(129680,'取消分享'),
          className: 'wea-doc-netdisk-right-button',
          style: { backgroundColor: '#FE0103',},
          onPress: () => this.cancelMyShare(rowData.type==='folder'?{folderids:rowData.id}:{fileids:rowData.id})
        });
      }
    } else {
      buttons.push({
        text: getLabel(390470,'保存到我的云盘'),
        className: 'wea-doc-netdisk-right-button',
        style: { backgroundColor: '#2285FE',},
        onPress: ()=>this.goCategoryBrowser((rowData, id, name) => {
          let params = {folderid: id};
          if (rowData.type === 'folder') {
            params.folderids = rowData.id;
          } else {
            params.fileids = rowData.id;
          }
          this.saveToMyNetdisk(id,rowData)
        }, history, rowData, {sharetype: 'disk'})
        // () => this.saveToMyNetdisk()
      });
    }
    return buttons;
  }
  
  //查看分享对象
  getShareWithList = (history,rowData) => {
    this.shareObjPageData = rowData;
    history.push(`${this.path}/myshare/userlist`);
  }
  //取消分享
  cancelMyShare = (params) =>{
    Modal.alert(getLabel(24960,'提示信息'),getLabel(390471, "确定要取消分享吗？"), [
      { text: getLabel(31129, '取消')},
      { text: getLabel(826, '确定'), onPress: () => {
          API.cancelShare(params).then((result)=>{
            Bubble.success(getLabel(30700, '操作成功'));
            //取消分享后更新列表
            this.getList();
          })
        }
      },
    ])
  }
  //保存到我的云盘
  saveToMyNetdisk = (id,rowData) => {
   let folderids = '';
   let fileids = '';
   if(rowData.type === 'folder'){
    folderids = rowData.id;
   }else{
    fileids = rowData.id;
   }
    API.saveToMy({folderid:id,fileids,folderids}).then((result)=>{
      Bubble.success(getLabel(30700, '操作成功'));
    })
  }
  
  publish = (categoryid,rowData) => {
    let params = {method:"public",category:categoryid};
    if (rowData.type === 'file') {
      params.fileids = rowData.id;
    } else {
      params.folderids = rowData.id;
    }
    return API.publish(params).then((result) =>{
      Bubble.success(getLabel(33179, "发布成功"), 2);
    });
  }
  
  delForSingle = (rowData) => {
    Modal.alert(getLabel(24960,'提示信息'), getLabel(388758, "确认要删除吗?"), [
      { text: getLabel(31129, '取消')},
      { text: getLabel(826, '确定'), onPress: () => {
          let params = {};
          if (rowData.type === 'folder') {
            params.folderids = rowData.id;
          } else {
            params.fileids = rowData.id;
          }
          this.del(params);
        }
      },
    ])
  }
  
  del = (params) => {
    return API.del(params).then((result) => {
      if (result.msg) {
        Bubble.error(result.msg);
      } else {
        Bubble.success(getLabel(20461, '删除成功'));
        this.getList();
      }
    })
  }

  setChild = (categoryInfo) => {
    this.searchCategoryInfo = categoryInfo;
    if (categoryInfo) {
      let promise;
      if (categoryInfo.id && !categoryInfo.name) {
        promise = API.getInfo({id: categoryInfo.id}).then((result) => {
          if (result.isCurrentUser) {
            this.netdiskStore.setSelectedTab('disk');
          } else {
            this.netdiskStore.setSelectedTab('shareMy');
          }
          let category = {
            id: result.id,
            name: result.categoryname,
            parentId: result.parentid,
          };
          return category;
        });
      } else {
        promise = new Promise((resolve) => {
          categoryInfo = {...categoryInfo,parentId:categoryInfo.pid,name:categoryInfo.name}
          resolve(categoryInfo);
        });
      }
      return promise.then((result) => {
        this.child = new ListStore({categoryInfo: result, netdiskStore: this.netdiskStore, parent: this});
        // let searchParams = {};
        // if(categoryInfo && categoryInfo.bySearch){
        //   searchParams = {...searchParams,keyword:categoryInfo.keyword,folderid:categoryInfo.folderid,bySearch:"1"}
        // }
        this.child.getList();
      })
    } else {
      this.child = null;
      return new Promise((resolve) => resolve());
    }
  }

  setInputElliVisible = (visible) => {
    this.inputElliVisible = visible;
  }

  selectInputElli = (item, index) => {
    this.inputElliVisible = false;
    if (item.key === 'add') {
      this.showCategoryInfo();
    } else {
      this.netdiskStore.multiOper = true;
      this.updateList();
    }
  }
  
  showCategoryInfo = () => {
    let parentId = this.categoryInfo ? this.categoryInfo.id : '';
    Modal.prompt(
      getLabel(20002, '新建目录'),
      '',
      [{text: getLabel(31129, "取消")}, {text: getLabel(826, "确定"), onPress: (name) => this.saveCategoryInfo({parentId, name})}],
      null,
      null,
      [getLabel(129186, '请输入目录名称')],
    );
    this.inputElliVisible = false;
  }
  saveCategoryInfo = (params) => {
    if (!params.name) {
      Toast.fail(getLabel(129186, "请输入目录名称"), 1, null, false);
      return new Promise((resolve, reject) => reject(getLabel(129186, "请输入目录名称")));
    }
    return API.saveCategory({...params,folderid:params.parentId}).then((result) => {
      Toast.success(getLabel(22619, "保存成功"), 1, null, false);
      this.getList();
    });
  }
  
  cancelMultiOper = () => {
    this.netdiskStore.multiOper = false;
    this.chooseIds = [];
    this.chooseRows = [];
    this.updateList();
  }
  
  choose = (data) => {
    let prevChooseIds = toJS(this.chooseIds),
      chooseIds = prevChooseIds.filter((id) => id !== `${data.type}-${data.id}`),
      chooseRows = toJS(this.chooseRows);
    if (chooseIds.length === prevChooseIds.length) {
      chooseIds.push(`${data.type}-${data.id}`);
      chooseRows.push(data)
    } else {
      chooseRows = chooseRows.filter((row) => row.id !== `${data.type}-${data.id}`);
    }
    this.chooseIds = chooseIds;
    this.chooseRows = chooseRows;
    this.updateList();
  }
  chooseAll = () => {
    let all = [
      ...toJS(this.folderList).map((item) => {return {...item, type: 'folder'}}),
      ...toJS(this.fileList).map((item) => {return {...item, type: 'file'}}),
    ];
    this.chooseIds = all.map((item) => `${item.type}-${item.id}`);
    this.chooseRows = all;
    this.updateList();
  }
  
  chooseNone = () => {
    this.chooseIds = [];
    this.chooseRows = [];
    this.updateList();
  }
  
  updateList = () => {
    this.datasource = this.datasource.cloneWithRows([
      ...toJS(this.folderList).map((item) => (
          {
            ...item,
            type: 'folder',
          }
        )),
      ...toJS(this.fileList).map((item) => (
        {
          ...item,
          type: 'file',
        }
      )),
    ]);
  }

  getChild = () => {
    if (this.child) {
      return this.child.getChild();
    }
    return this;
  }
  
  multiShare = (history) => {
    if (this.chooseRows.length === 0) {
      Bubble.warning(getLabel(391246,'请选择要分享的数据'), 2);
      return;
    }
    let chooseRows = toJS(this.chooseRows);
    let msgInfoList = chooseRows.map((rowData) => ({
      content: rowData.name, // 分享标题（必填）
      desc: "", // 分享描述（非必填）
      sysid: window.localStorage.emobile_ec_id, // EM中添加的集成系统的ID (必填: 按照demo给的传)
      linkurl: rowData.type === 'file' ?  // 消息链接地址（必填）
        `/spa/document/static4mobile/index.html#/netdisk/file/attach/${rowData.id}?resource=${'em'}&type=${'file'}&fid=${rowData.id}`:
        `/spa/document/static4mobile/index.html#/netdisk/${rowData.id}?resource=${'em'}&type=${'folder'}&fid=${rowData.id}`
      ,
      // linkurl_pc: ``, //PC端消息链接地址，如果没有则取linkurl值
      canforward:1, // 消息是否允许转发 1：是（默认） 0：否
      callbackurl:`/api/networkdisk/clouddisk/share?${rowData.type === 'file' ? 'fileids' : 'folderids'}=${rowData.id}`, // 消息转发回调地址（非必填）
      opentype:1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
      opentype_pc:rowData.type === 'file' ? 2 : 1, //PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
      sharetype:rowData.type === 'file' ? "pdoc" : "folder", // 分享数据类型："doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
      shareid: rowData.id // 分享的数据ID（必填）
    }));
    this.shareParams = {};
    this.shareParams.folderids = chooseRows.filter((item) => item.type === 'folder').map((item) => item.id).join();
    this.shareParams.fileids = chooseRows.filter((item) => item.type === 'file').map((item) => item.id).join();
    this.setShareData(msgInfoList);
    history.push(this.shareStore.path);
  }
  
  multiPublish = (id) => {
    if (this.chooseRows.length === 0) {
      Bubble.warning(getLabel(390472,'请选择要发布的数据'), 2);
      return;
    }
    let params = {};
    let chooseRows = toJS(this.chooseRows);
    params.folderids = chooseRows.filter((item) => item.type === 'folder').map((item) => item.id).join();
    params.fileids = chooseRows.filter((item) => item.type === 'file').map((item) => item.id).join();
    params.category = id;
    params.method = 'public';
    API.publish(params).then((result) =>{
      Bubble.success(getLabel(33179, "发布成功"), 2);
      this.cancelMultiOper();
    });
  }
  
  multiDelete = () => {
    if (this.chooseRows.length === 0) {
      Bubble.warning(getLabel(30951,'请选择需要删除的数据!'), 2);
      return;
    }
    Modal.alert(getLabel(24960,'提示信息'), getLabel(33435, "确定要删除选中的记录吗?"), [
      { text: getLabel(31129, '取消')},
      { text: getLabel(826, '确定'), onPress: () => {
          let params = {};
          let chooseRows = toJS(this.chooseRows);
          params.folderids = chooseRows.filter((item) => item.type === 'folder').map((item) => item.id).join();
          params.fileids = chooseRows.filter((item) => item.type === 'file').map((item) => item.id).join();
          this.del(params).then(() => {
            this.cancelMultiOper();
          });
        }
      },
    ])
  }
  
  multiMove = (history) => {
    if (this.chooseRows.length === 0) {
      Bubble.warning(getLabel(390473,'请选择要移动的数据'), 2);
      return;
    }
    let view = this.netdiskStore.selectedTab;
    let chooseRows = toJS(this.chooseRows), params = {};
    params.folderids = chooseRows.filter((item) => item.type === 'folder').map((item) => item.id).join();
    params.fileids = chooseRows.filter((item) => item.type === 'file').map((item) => item.id).join();
    this.goCategoryBrowser((id, name) => {
      params.folderid = id;
      if(view==='shareMy'){
        API.saveToMy(params).then((result)=>{
          Bubble.success(getLabel(30700, '操作成功'));
          this.getList();
          this.cancelMultiOper();
        })
      }else{
        API.move(params).then(() => {
          Bubble.success(getLabel(30700, '操作成功'));
          this.getList();
          this.cancelMultiOper();
        });
      }
    }, history, null, {noClick: params.folderids})
  }
  
  upload = (ids, datas) => {
    this.uploadList = datas;
     API.uploadToCloudDisk({imgFileId: ids.join(), seccategory: this.categoryInfo ? this.categoryInfo.id : ''}).then((res) => {
      if(!res.api_status){
        Bubble.error(res.msg);
      }else{
        this.getList();
        this.uploadList = [];// 保证上传组件第二次上传时第一次的数据已经清掉了。
      }
    })
  }
  
  goCategoryBrowser = (func, history, item, dataParams) => {
    this.categoryOper = {
      oper: func,
      item,
      dataParams
    };
    history.push(this.categoryBrowser.path);
  }
  goBrowser = (func, history, item) => {
    this.browserOper = {
      oper: func,
      item
    };
    history.push(this.browser.path);
  }
  chooseSystemCategory = (...args) => {
    if (this.browserOper.oper) {
      if (this.browserOper.item) {
        this.browserOper.oper(this.browserOper.item, ...args);
      } else {
        this.browserOper.oper(...args);
      }
    }
  }
  
  chooseCategory = (...args) => {
    if (this.categoryOper.oper) {
      if (this.categoryOper.item) {
        this.categoryOper.oper(this.categoryOper.item, ...args);
      } else {
        this.categoryOper.oper(...args);
      }
    }
  }
  
  setShareData = (x) => {
    this.shareData = x;
  }
  //=====================我的分享对象页面=================
   //添加搜索历史
   addHistory = (keyword,resource) =>{
    HistoryApi.addHistory({searchtext:keyword,type:resource==="search"?this.searchType:this.shareSearchType}) 
  }
  //获取搜索历史
  getHistory = (resource) => {
    const params = {type:resource==="search"?this.searchType:this.shareSearchType}; 
    HistoryApi.getHistoryList(params).then((result) => {
        this.historyList = [];
        result.historyData.map((data,i)=>{
          return this.historyList.push({
            key : i,
            name : data,
          });
        });
        if(resource==="search"){
          this.myDiskSearchPage.list.setState({data : this.historyList});
        }else{
          this.myShareSearchPage.list.setState({data : this.historyList});
        }
        
    }); 
  }
  //初始化搜索历史
  setSearchHistory = (resource) => {
    const template = {
      default: [
        {
          key: 'col1',
          configs: [
            {
              key: 'col1_row1',
              configs: [
                { key: 'name' },
              ],
            },
          ],
        },
      ],
    };
    if(resource==="search"){
      this.myDiskSearchPage.setState({ template });
    }else{
      this.myShareSearchPage.setState({ template });
    }
    this.getHistory(resource);
  }
    //搜索
    folderDoSearchByKeyword = (keyword,folderid) => {
      let params = {keyword : keyword,bySearch : keyword ? 1 : 0}
      this.myDiskSearchKey = params ? params : {}
      params = {...params,folderid}
      // this.netdiskStore.setSelectedTab(this.netdiskStore.selectedTab,params)
      let categoryInfo = toJS(this.searchCategoryInfo);
      categoryInfo = {...categoryInfo,keyword,folderid:"",bySearch:"1"}
      this.getList(categoryInfo)
      // this.setChild(categoryInfo);
    }
    //搜索
  doSearchByKeyword = (keyword) => {
    let params = {keyword : keyword,bySearch : keyword ? 1 : 0};
    this.searchKey = params ? params : {};
    this.getShareObjList();
  }
  //清空搜索历史
  clearSearchHistory = (resource) => {
    const params = {type:resource==="search"?this.searchType:this.shareSearchType}; 
    HistoryApi.clearSearchHistory(params).then((result) => {
        this.historyList = [];
        if(resource==="search"){
          this.myDiskSearchPage.list.setState({data : this.historyList});
        }else{
          this.myShareSearchPage.list.setState({data : this.historyList});
        }
    }); 
  }
  //获取分享对象信息
  getShareObjList = () =>{
    let rowData = toJS(this.shareObjPageData);
    let params = rowData && (rowData.type==='folder'?{folderid:rowData.id}:{fileid:rowData.id});
    let objname = this.searchKey && (this.searchKey.keyword || '');
    params = {...params,objname}
    API.getShareWithList(params).then((result)=>{
      let objList = result && result.dataList;
      this.shareObjLVPStore.setState({
        loading: false,
        data: toJS(objList),
        isTable: false,
        // hasMore: result.docs.length > 0,
      });
      this.shareObjLVPStore.updateDataSource();
    })
  }
  //批量操作分享对象
  chooseShareObj = (rowData) =>{
    let prevChooseIds = toJS(this.shareObjChooseIds);
    let shareObjChooseIds = prevChooseIds.filter((id) => id !== rowData.id);
    let shareObjRows = toJS(this.shareObjRows);
    if(shareObjChooseIds.length === prevChooseIds.length){
      shareObjChooseIds.push(rowData.id);
      shareObjRows.push(rowData);
    }else{
      shareObjRows = shareObjRows.filter((row) => row.id !== rowData.id);
    }
    this.shareObjLVPStore.select(shareObjChooseIds);
    this.shareObjChooseIds = shareObjChooseIds;
    this.shareObjRows = shareObjRows;
  }
  //全选
  chooseAllShareObj = (alldata) =>{
    let prevChooseIds = [];
    alldata.map((val)=>{
      prevChooseIds.push(val.id);
      return val;
    })
    this.shareObjChooseIds = prevChooseIds;
  }
  //清除数据
  clearShareObjData = () =>{
    this.shareObjChooseIds = [];
    this.shareObjRows = [];
    this.shareObjLVPStore.selectNone();
  }
  //删除分享对象
  deleteShareObj = () =>{
    let prevChooseIds = toJS(this.shareObjChooseIds);
    let preshareObjRows = toJS(this.shareObjRows);
    prevChooseIds.length
    ? Modal.alert(getLabel(24960,'提示信息'), getLabel(391327, "删除所选项?"), [
      { text: getLabel(31129, '取消')},
      { text: getLabel(826, '确定'), onPress: () => {
        //逗号隔开的形式传入shareid
          let shareids = '';
          let toSharerid = '';
          prevChooseIds.map((id,index) =>{
            shareids = index === 0 ? id : shareids+','+id;
            return id;
          })
          preshareObjRows.map((val,index)=>{
            toSharerid = index === 0 ? val.shareid : toSharerid + ',' + val.shareid;
            return val;
          })
          let rowData = toJS(this.shareObjPageData);
          let params = rowData.type==='folder'?{folderid:rowData.id}:{fileid:rowData.id}
          params = {...params,shareids,toSharerid}
          API.deleteShareObj(params).then((result)=>{
            Bubble.success(getLabel(30700, '操作成功'));
            //清空选择的数据
            this.shareObjChooseIds = [];
            //刷新分享对象信息
            this.getShareObjList();
            //刷新我的分享页面信息
            this.getList();
          })
        }
      },
    ])
    :Bubble.warning(getLabel(30951,'请选择需要删除的数据！'), 2);
  }
//==================
////获取文件/目录的查看权限
  getShareIsReader = (params) =>{
    return API.checkShare(params).then((result) =>{
      if(result){
        this.canReader = result.canReader;
        this.shareCancle = result.shareCancle;
        this.fileDel = result.fileDel;
      } 
    });
  }

  getNextPageList = () =>{
    // console.log(toJS(this.myDiskSearchKey));
    let myDiskSearchKey = toJS(this.myDiskSearchKey);
    let keyword = (myDiskSearchKey && myDiskSearchKey.keyword) ? myDiskSearchKey.keyword :"";
    if(keyword===""){
      this.currentPageNum ++;
      this.getList({pageNum:toJS(this.currentPageNum),isScroll:"1"})
    }else{
      this.folderDoSearchByKeyword(keyword,"")
    }
  }
  getonRefresh = () =>{
    let myDiskSearchKey = toJS(this.myDiskSearchKey);
    let keyword = (myDiskSearchKey && myDiskSearchKey.keyword) ? myDiskSearchKey.keyword :"";
    if(keyword===""){
      this.getList();
    }else{
      this.folderDoSearchByKeyword(keyword,"")
    }
  }
}